<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>获取数据</button>
    <script>
        // 定义ajax函数
        function ajax(url) {
            return new Promise((resolve, reject) => {
                let x = new XMLHttpRequest();
                x.open('GET', url);
                x.send();
                x.responseType = 'json';
                x.onreadystatechange = function () {
                    if (x.readyState === 4) {
                        if (x.status >= 200 && x.status < 300) {
                            resolve({
                                data:x.response,
                                status:x.status,
                                statusText:x.statusText,
                                headers:x.getAllResponseHeaders(),
                            });
                        }else{
                            reject(x.statusText);
                        }
                    }
                }
            });
        }

        // 第一种使用方式
        // ajax('https://v1.hitokoto.cn/?c=a')
        // .then(val=>{
        //     console.log(val.hitokoto);
        // });

        // (async function(){
        //     let result = await ajax('https://v1.hitokoto.cn/?c=a');
        //     console.log(result);
        // })()


        let btn = document.querySelector('button');

        btn.onclick =async ()=>{
            let result = await ajax('https://v1.hitokoto.cn/?c=a');
            console.log(result.data.hitokoto);
        }


    </script>
</body>

</html>